<template>
  <div class="payment-container">
    <!-- 搜索区域 -->
    <el-card class="search-card">
      <el-form :model="searchForm" inline>
        <el-form-item label="账户ID">
          <el-input v-model="searchForm.accountId" placeholder="请输入账户ID" clearable />
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="searchForm.status" placeholder="请选择状态" clearable>
            <el-option label="待审核" :value="0" />
            <el-option label="已审核" :value="1" />
            <el-option label="已拒绝" :value="2" />
          </el-select>
        </el-form-item>
        <el-form-item label="日期范围">
          <el-date-picker
            v-model="searchForm.dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 统计卡片 -->
    <el-row :gutter="20" class="stats-row">
      <el-col :span="6">
        <el-card class="stats-card">
          <div class="stats-item">
            <div class="stats-title">总付款金额</div>
            <div class="stats-value">¥{{ stats.totalAmount || '0.00' }}</div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="stats-card">
          <div class="stats-item">
            <div class="stats-title">本月付款</div>
            <div class="stats-value">¥{{ stats.monthlyAmount || '0.00' }}</div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="stats-card">
          <div class="stats-item">
            <div class="stats-title">待审核</div>
            <div class="stats-value">{{ stats.pendingCount || 0 }}</div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="stats-card">
          <div class="stats-item">
            <div class="stats-title">已审核</div>
            <div class="stats-value">{{ stats.approvedCount || 0 }}</div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 操作按钮 -->
    <el-card class="action-card">
      <el-button type="primary" @click="handleAdd">新增付款单</el-button>
      <el-button type="success" @click="handleBatchApprove" :disabled="!selectedIds.length">
        批量审核
      </el-button>
      <el-button type="danger" @click="handleBatchDelete" :disabled="!selectedIds.length">
        批量删除
      </el-button>
      <el-button @click="handleExport">导出Excel</el-button>
    </el-card>

    <!-- 数据表格 -->
    <el-card class="table-card">
    

      <!-- 数据表格 -->
      <el-table
        v-loading="loading"
        :data="Array.isArray(tableData) ? tableData : []"
        @selection-change="handleSelectionChange"
        border
        stripe
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="billNo" label="单据编号" width="150" />
        <el-table-column prop="accountId" label="账户ID" width="120" />
        <el-table-column prop="amount" label="付款金额" width="120">
          <template #default="{ row }">
            ¥{{ row.amount || '0.00' }}
          </template>
        </el-table-column>
        <el-table-column prop="flowType" label="流水类型" width="120" />
        <el-table-column prop="createTime" label="创建日期" width="140">
          <template #default="{ row }">
            {{ formatDate(row.createTime) }}
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="getStatusType(row.status)">
              {{ getStatusText(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="remark" label="备注" show-overflow-tooltip />
        <!-- 去掉未定义的 formatDateTime，统一用日期 -->
        <el-table-column prop="createTime" label="创建日期" width="140">
          <template #default="{ row }">
            {{ formatDate(row.createTime) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" size="small" @click="handleView(row)">查看</el-button>
            <el-button type="warning" size="small" @click="handleEdit(row)">编辑</el-button>
            <el-button
              v-if="row.status === 0"
              type="success"
              size="small"
              @click="handleApprove(row)"
            >
              审核
            </el-button>
            <el-button type="danger" size="small" @click="handleDelete(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pagination.current"
          v-model:page-size="pagination.size"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 新增/编辑对话框 -->
    <el-dialog
      v-if="dialogVisible"
      v-model="dialogVisible"
      :title="dialogType === 'add' ? '新增付款单' : dialogType === 'edit' ? '编辑付款单' : '查看付款单'"
      width="600px"
      :close-on-click-modal="false"
      :destroy-on-close="true"
      :append-to-body="true"
    >
      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="100px"
        :disabled="dialogType === 'view'"
      >
        <el-form-item label="单据编号" prop="billNo">
          <el-input v-model="form.billNo" placeholder="请输入单据编号">
            <template #append>
              <el-button @click="generateBillNo" :disabled="dialogType === 'view'">自动生成</el-button>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item label="账户ID" prop="accountId">
          <el-input v-model="form.accountId" placeholder="请输入账户ID" type="number" />
        </el-form-item>
        <el-form-item label="流水类型" prop="flowType">
          <el-select v-model="form.flowType" placeholder="请选择流水类型" style="width: 100%">
            <el-option label="收入" value="income" />
            <el-option label="支出" value="expense" />
          </el-select>
        </el-form-item>
        <el-form-item label="金额" prop="amount">
          <el-input-number
            v-model="form.amount"
            :precision="2"
            :step="100"
            :min="0"
            style="width: 100%"
            placeholder="请输入金额"
          />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input
            v-model="form.remark"
            type="textarea"
            :rows="3"
            placeholder="请输入备注信息"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button v-if="dialogType !== 'view'" type="primary" @click="handleSubmit">
            确定
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getAccountFlowList, addAccountFlow, updateAccountFlow, deleteAccountFlow, approveAccountFlow, batchDeleteAccountFlow, batchApproveAccountFlow, exportAccountFlow, getAccountFlowStats } from '@/api/finance/accountFlow'

// 响应式数据
const loading = ref(false)
const tableData = ref([])
const selectedIds = ref([])
const dialogVisible = ref(false)
const dialogType = ref('add') // add, edit, view
const formRef = ref(null)
const stats = reactive({
  totalAmount: '0.00',
  monthlyAmount: '0.00',
  pendingCount: 0,
  approvedCount: 0
})

// 统计数据
const totalPayment = ref(0)

// 表单数据
const form = reactive({
  id: null,
  billNo: '',
  accountId: '',
  billType: 'payment',
  flowType: 'expense',
  amount: 0,
  remark: ''
})

// 表单验证规则
const rules = {
  billNo: [{ required: true, message: '请输入单据编号', trigger: 'blur' }],
  accountId: [{ required: true, message: '请输入账户ID', trigger: 'blur' }],
  amount: [{ required: true, message: '请输入金额', trigger: 'blur' }]
}

// 搜索表单
const searchForm = reactive({
  accountId: '',
  status: '',
  dateRange: []
})

// 分页配置
const pagination = reactive({
  current: 1,
  size: 10,
  total: 0
})

// 获取数据
const loadData = async () => {
  loading.value = true
  try {
    const params = {
      pageNum: pagination.current,
      pageSize: pagination.size,
      billType: 'payment', // 付款单类型
      ...searchForm,
      startDate: searchForm.dateRange?.[0],
      endDate: searchForm.dateRange?.[1]
    }
    
    const response = await getAccountFlowList(params)
    
    // 检查响应格式
    if (response && response.code === 200 && response.data) {
      // 标准Result格式
      const page = response.data
      tableData.value = page?.records || []
      pagination.total = page?.total || 0
    } else if (response && response.records) {
      // 直接Page格式（兼容性）
      tableData.value = response.records || []
      pagination.total = response.total || 0
    } else {
      console.error('API返回错误:', response)
      ElMessage.error('获取数据失败：数据格式不正确')
      tableData.value = []
      pagination.total = 0
    }
  } catch (error) {
    console.error('获取付款单数据失败:', error)
    ElMessage.error('获取数据失败')
    tableData.value = []
    pagination.total = 0
  } finally {
    loading.value = false
  }
}

// 获取统计数据
const loadStats = async () => {
  try {
    const params = { billType: 'payment' }
    const response = await getAccountFlowStats(params)
    
    let data
    // 检查响应格式
    if (response && response.code === 200 && response.data) {
      // 标准Result格式
      data = response.data
    } else if (response && response.records !== undefined) {
      // 直接数据格式（兼容性）
      data = response
    } else {
      console.error('统计数据响应格式错误:', response)
      data = { records: [] }
    }
    
    const records = Array.isArray(data?.records) ? data.records : []
    // 计算统计数据
    const totalAmount = records.reduce((sum, item) => sum + (parseFloat(item.amount) || 0), 0)
    const currentMonth = new Date().getMonth() + 1
    const currentYear = new Date().getFullYear()
    const monthlyAmount = records.reduce((sum, item) => {
      if (item.createTime) {
        const createDate = new Date(item.createTime)
        if (createDate.getMonth() + 1 === currentMonth && createDate.getFullYear() === currentYear) {
          return sum + (parseFloat(item.amount) || 0)
        }
      }
      return sum
    }, 0)
    // AccountFlow没有status字段，这里暂时设为0
    const pendingCount = 0
    const approvedCount = records.length
    
    // 更新totalPayment变量
    totalPayment.value = totalAmount
    
    Object.assign(stats, {
      totalAmount: totalAmount.toFixed(2),
      monthlyAmount: monthlyAmount.toFixed(2),
      pendingCount,
      approvedCount
    })
  } catch (error) {
    console.error('获取统计数据失败:', error)
    Object.assign(stats, {
      totalAmount: '0.00',
      monthlyAmount: '0.00',
      pendingCount: 0,
      approvedCount: 0
    })
  }
}

// 搜索
const handleSearch = () => {
  pagination.current = 1
  loadData()
  loadStats()
}

// 重置
const handleReset = () => {
  Object.assign(searchForm, {
    accountId: '',
    status: '',
    dateRange: []
  })
  pagination.current = 1
  loadData()
  loadStats()
}

// 分页处理
const handleSizeChange = (size) => {
  pagination.size = size
  pagination.current = 1
  loadData()
}

const handleCurrentChange = (current) => {
  pagination.current = current
  loadData()
}

// 选择处理
const handleSelectionChange = (selection) => {
  selectedIds.value = selection.map(item => item.id)
}

// 新增
const handleAdd = async () => {
  dialogType.value = 'add'
  resetForm()
  dialogVisible.value = true
  // 自动生成单据编号
  await generateBillNo()
}

// 查看
const handleView = (row) => {
  dialogType.value = 'view'
  Object.assign(form, row)
  dialogVisible.value = true
}

// 编辑
const handleEdit = (row) => {
  dialogType.value = 'edit'
  Object.assign(form, row)
  dialogVisible.value = true
}

// 删除
const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm('确定要删除这条付款单吗？', '提示', {
      type: 'warning'
    })
    
    await deleteAccountFlow(row.id)
    ElMessage.success('删除成功')
    loadData()
    loadStats()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除付款单失败:', error)
      ElMessage.error('删除失败')
    }
  }
}

// 审核
const handleApprove = async (row) => {
  try {
    await ElMessageBox.confirm('确定要审核这条付款单吗？', '提示', {
      type: 'warning'
    })
    
    await approveAccountFlow(row.id)
    ElMessage.success('审核成功')
    loadData()
    loadStats()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('审核付款单失败:', error)
      ElMessage.error('审核失败')
    }
  }
}

// 批量删除
const handleBatchDelete = async () => {
  if (!selectedIds.value.length) {
    ElMessage.warning('请选择要删除的付款单')
    return
  }
  
  try {
    await ElMessageBox.confirm(`确定要删除选中的 ${selectedIds.value.length} 条付款单吗？`, '提示', {
      type: 'warning'
    })
    
    await batchDeleteAccountFlow(selectedIds.value)
    ElMessage.success('批量删除成功')
    loadData()
    loadStats()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('批量删除付款单失败:', error)
      ElMessage.error('批量删除失败')
    }
  }
}

// 批量审核
const handleBatchApprove = async () => {
  if (!selectedIds.value.length) {
    ElMessage.warning('请选择要审核的付款单')
    return
  }
  
  try {
    await ElMessageBox.confirm(`确定要审核选中的 ${selectedIds.value.length} 条付款单吗？`, '提示', {
      type: 'warning'
    })
    
    const res = await batchApproveAccountFlow(selectedIds.value)
    if (res.data.code === 200) {
      ElMessage.success('批量审核成功')
      loadData()
      loadStats()
    } else {
      ElMessage.error(res.data.message || '批量审核失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('批量审核付款单失败:', error)
      ElMessage.error('批量审核失败')
    }
  }
}

// 表单提交
const handleSubmit = async () => {
  try {
    // 表单验证
    await formRef.value.validate()
    
    if (dialogType.value === 'add') {
      await addAccountFlow(form)
    } else {
      await updateAccountFlow(form)
    }
    ElMessage.success(dialogType.value === 'add' ? '新增成功' : '编辑成功')
    dialogVisible.value = false
    loadData()
    loadStats()
  } catch (error) {
    console.error('提交失败:', error)
    ElMessage.error('提交失败')
  }
}

// 重置表单
const resetForm = () => {
  Object.assign(form, {
    id: null,
    billNo: '',
    accountId: '',
    billType: 'payment',
    flowType: 'expense',
    amount: 0,
    remark: ''
  })
}

// 自动生成单据编号
const generateBillNo = async () => {
  try {
    // 获取当前日期
    const now = new Date()
    const year = now.getFullYear()
    const month = String(now.getMonth() + 1).padStart(2, '0')
    const day = String(now.getDate()).padStart(2, '0')
    const dateStr = `${year}${month}${day}`
    
    // 获取今天的单据数量作为序号
    const today = `${year}-${month}-${day}`
    const params = {
      pageNum: 1,
      pageSize: 1000,
      billType: 'payment',
      startDate: today,
      endDate: today
    }
    
    const page = await getAccountFlowList(params)
    const todayRecords = page?.records || []
    const todayCount = todayRecords.length + 1
    const sequence = String(todayCount).padStart(3, '0')
    // 生成单据编号：FK + 年月日 + 3位序号
    const billNo = `FK${dateStr}${sequence}`
    form.billNo = billNo
    ElMessage.success('单据编号生成成功')
  } catch (error) {
    console.error('生成单据编号失败:', error)
    // 如果出错，使用时间戳作为序号
    const now = new Date()
    const year = now.getFullYear()
    const month = String(now.getMonth() + 1).padStart(2, '0')
    const day = String(now.getDate()).padStart(2, '0')
    const dateStr = `${year}${month}${day}`
    const timestamp = Date.now().toString().slice(-3)
    const billNo = `FK${dateStr}${timestamp}`
    form.billNo = billNo
    ElMessage.success('单据编号生成成功')
  }
}

// 导出
const handleExport = async () => {
  try {
    // 检查是否有数据可以导出
    if (!tableData.value || tableData.value.length === 0) {
      ElMessage.warning('暂无数据可导出，请先加载数据')
      return
    }
    
    ElMessage.info('正在导出付款管理数据，请稍候...')
    
    // 准备CSV数据
    const headers = ['流水号', '流水类型', '金额', '创建时间', '单据类型', '单据编号', '备注']
    const dataList = []
    
    // 添加数据行
    tableData.value.forEach(row => {
      dataList.push([
        row.id || '',
        row.flowType === 'income' ? '收入' : '支出',
        row.amount || 0,
        row.createTime || '',
        row.billType || '',
        row.billNo || '',
        row.remark || ''
      ])
    })
    
    // 添加汇总行
    dataList.push([
      '总计',
      '',
      totalPayment.value || 0,
      '',
      `记录数: ${pagination.total || 0}`,
      '',
      ''
    ])
    
    // 创建CSV文件并下载
    const workbook = new Blob([
      '\uFEFF' + // BOM for UTF-8
      headers.join(',') + '\n' +
      dataList.map(row => row.join(',')).join('\n')
    ], { type: 'text/csv;charset=utf-8;' })
    
    const url = window.URL.createObjectURL(workbook)
    const link = document.createElement('a')
    link.href = url
    link.download = `付款管理数据_${new Date().toISOString().slice(0, 10)}.csv`
    link.click()
    window.URL.revokeObjectURL(url)
    
    ElMessage.success('导出成功')
    
  } catch (error) {
    console.error('导出失败:', error)
    ElMessage.error('导出失败：' + error.message)
  }
}

// 工具函数
const formatDate = (date) => {
  if (!date) return ''
  const d = new Date(date)
  if (isNaN(d)) return String(date).slice(0, 10)
  const y = d.getFullYear()
  const m = String(d.getMonth() + 1).padStart(2, '0')
  const day = String(d.getDate()).padStart(2, '0')
  return `${y}-${m}-${day}`
}

const getStatusType = (status) => {
  const statusMap = {
    0: 'warning',
    1: 'success',
    2: 'danger'
  }
  return statusMap[status] || 'info'
}

const getStatusText = (status) => {
  const statusMap = {
    0: '待审核',
    1: '已审核',
    2: '已拒绝'
  }
  return statusMap[status] || '未知'
}

// 初始化
onMounted(() => {
  loadData()
  loadStats()
})
</script>

<style scoped>
.payment-container {
  padding: 20px;
}

.search-card {
  margin-bottom: 20px;
}

.stats-row {
  margin-bottom: 20px;
}

.stats-card {
  text-align: center;
}

.stats-item {
  padding: 10px;
}

.stats-title {
  font-size: 14px;
  color: #666;
  margin-bottom: 8px;
}

.stats-value {
  font-size: 24px;
  font-weight: bold;
  color: #409eff;
}

.table-card {
  margin-bottom: 20px;
}

.table-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.table-title {
  font-size: 18px;
  font-weight: bold;
}

.table-actions {
  display: flex;
  gap: 10px;
}

.pagination-container {
  margin-top: 20px;
  text-align: right;
}
</style> 